﻿using System;
using System.Web.Mvc;

namespace Knight.Web.Infrastructure.Menus
{
    public class MallAdminMenuAttribute : FilterAttribute, IResultFilter
    {
        readonly string _menuId = "";
        public MallAdminMenuAttribute()
        { }
        public MallAdminMenuAttribute(string menuId)
        {
            this._menuId = menuId;
        }

        public void OnResultExecuted(ResultExecutedContext filterContext)
        {

        }

        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            if (filterContext.Result is ViewResult)
            {
                var viewBag = filterContext.Controller.ViewBag;
                //填充当前的菜单ID
                viewBag.CurrentMenuID = _menuId;

                //填充当前的所有的菜单
                var menu = MenuProvider.MallAdminMenu;
                viewBag.Menu = menu;

                var mi = MenuProvider.GetMallAdminItemItem(this._menuId);

                if (mi != null)
                {
                    if (mi.Children != null && mi.Children.Count > 0)
                    {
                        throw new ApplicationException(string.Format("不允许设置存在下级菜单的菜单项！"));
                    }

                    viewBag.ModuleTitle = mi.Title;
                }

                //计算出当前的菜单ID的位置
                var mis = MenuProvider.GetMallAdminAllMenuItemsBy(this._menuId);
                //设置模块的位置
                viewBag.Locations = mis;
            }
        }
    }
}
